/*
 * Copyright (C) 2018 The Asiainfo-Ability Authors
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 */

package org.asiainfo.ability.node.utils;

import java.io.*;

/**
 * @Author: visen
 * @Date: 2018/1/27
 * @Description:
 */
public class ShellUtils {

    private final static String EXIT = "___exit___";

    public static boolean isWinOs() {
        String osKey = System.getProperty("os.name");
        return osKey != null && osKey.toLowerCase().startsWith("win");
    }
    public static String invoke(String command) throws Exception {
        ProcessBuilder runner;
        if (isWinOs()) {
            runner = new ProcessBuilder("cmd.exe");
        } else {
            runner = new ProcessBuilder("sh");
        }
        Process process = null;
        PrintWriter writer = null;
        BufferedReader reader = null;
        try {
            //runner.directory(new File("c:/"));
            runner.redirectErrorStream(true);
            process = runner.start();

            writer = new PrintWriter(new OutputStreamWriter(process.getOutputStream()));

            //writer.println("javaw -jar E:\\cloud\\test\\v.jar > E:\\cloud\\test\\out1.log");
            writer.println(command);
            writer.println("echo " + EXIT);
            writer.flush();
            reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            String line;
            StringBuilder buf = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                if (line.indexOf(EXIT) > -1) {
                    break;
                }
                buf.append(line).append("\n");
                System.out.println(line);
            }
            return buf.toString();
        } catch (Exception e) {
            throw e;
        } finally {
            if (process != null) {
                try {
                    process.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                process.destroy();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (writer != null) {
                writer.close();
            }
        }
    }
}
